package com.aabte.auth.shared.messaging.consumer;

import com.aabte.auth.account.domain.event.AccountCreated;
import com.aabte.auth.account.domain.event.PasswordChanged;
import com.aabte.auth.event.model.StoredEvent;
import com.aabte.auth.event.repository.StoredEventRepository;
import com.aabte.commons.ddd.shared.DomainEvent;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Instant;

@Component
public class StoreApplicationEventConsumer {

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    @Resource
    private StoredEventRepository storedEventRepository;

    @EventListener(AccountCreated.class)
    public void accountCreated(AccountCreated event) throws Exception {
        store(event.identity(), event);
    }

    @EventListener(PasswordChanged.class)
    public void passwordChanged(PasswordChanged event) throws Exception {
        store(event.identity(), event);
    }

    private void store(String eventId, DomainEvent event) throws JsonProcessingException {
        String eventBody = OBJECT_MAPPER.writeValueAsString(event);
        StoredEvent storedEvent = new StoredEvent(eventId, event.getClass().getName(), eventBody, Instant.now());
        storedEventRepository.store(storedEvent);
    }

}
